<template>
	<view class="view-root">
		<u-empty-state v-if="validList.length == 0 && invalidList.length == 0" value="购物车是空的" style="flex: 1;"></u-empty-state>
		<scroll-view v-if="validList.length > 0 || invalidList.length > 0" class="content-scroll"  scroll-y="true">
			<view class="scroll-flex-wrap">
				<view v-if="validList.length > 0" class="valid-wrap">
					<view class="valid-title">
						<view class="checkbox_wrap" @click="checkAll()">
							<view class="checkbox_circle">
								<view v-if="allChecked"></view>
							</view>
						</view>
						<view class="valid-title-text">全选</view>
					</view>
					<view v-for="(medicine, index) in validList" :key="index" class="valid-medicine" @click="gotoRouter('/pages-mall/medicineDetail/medicineDetail?id=' + medicine.id)">
						<view class="checkbox_wrap" @click.stop="checkMedicine(medicine)">
							<view class="checkbox_circle">
								<view v-if="medicine.isChecked"></view>
							</view>
						</view>
						<view class="medicine-pic-wrap">
							<image :src="medicine.thumbnailUrl" class="medicine-pic"></image>
							<view v-if="medicine.recipeFlag > 0" class="prescription-tag">处方药</view>
						</view>
						<view class="info-wrap">
							<view class="medicine-name nowrap">{{medicine.name}}</view>
							<view class="medicine-pack">规格：{{medicine.specification}}</view>
							<view v-if="!editMode" class="price-count-line">
								<view class="price-show">￥{{medicine.salesPrice}}</view>
								<view style="flex: 1;"></view>
								<view class="minus-btn" @click.stop="changeCount(medicine, medicine.count - 1)">
									<image src="https://res.jiuzhang-cloud.com/jzy-oss/upload/image/dti-hospital/ic_cart_minus.png"></image>
								</view>
								<view class="count-show" @click.stop="showCountInput(medicine)">{{medicine.count}}</view>
								<view class="plus-btn" @click.stop="changeCount(medicine, medicine.count + 1)">
									<image src="https://res.jiuzhang-cloud.com/jzy-oss/upload/image/dti-hospital/ic_cart_plus.png"></image>
								</view>
							</view>
						</view>
					</view>
				</view>
				<view v-if="invalidList.length > 0" class="invalid-wrap">
					<view class="invalid-title">
						<view class="invalid-title-text">{{invalidList.length}}件失效商品</view>
						<view class="invalid-clear-text" @click="clearAllInvalid()">清空失效商品</view>
					</view>
					<view v-for="(medicine, index) in invalidList" :key="index" class="invalid-medicine">
						<view class="invalid-tag">失效</view>
						<view class="medicine-pic-wrap">
							<image :src="medicine.thumbnailUrl" class="medicine-pic"></image>
							<view v-if="medicine.recipeFlag > 0" class="prescription-tag">处方药</view>
						</view>
						<view class="info-wrap">
							<view class="medicine-name nowrap">{{medicine.name}}</view>
							<view class="medicine-pack">规格：{{medicine.specification}}</view>
							<view v-if="!editMode" class="price-count-line">
								<view class="price-show">￥{{medicine.salesPrice}}</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
		<view v-if="validList.length > 0 || invalidList.length > 0" class="bottom-panel">
			<view class="cart-edit-entry" @click="toEdit">{{editMode ? '完成': '管理'}}</view>
			<view style="flex: 1;"></view>
			<view v-if="editMode" class="cart-clear-btn" @click="clearAllMedicine()">清空购物车</view>
			<view v-if="!editMode" class="total-price-title">合计：</view>
			<view v-if="!editMode" class="total-price-show">￥{{selectedTotalPrice}}</view>
			<view class="confirm-btn" @click="doConfirm">{{editMode ? '删除': '提交'}}</view>
		</view>
		<view v-if="hasRecipeCheck" class="recipe-notice">
			<view class="notice-content-wrap">
				<image src="https://res.jiuzhang-cloud.com/jzy-oss/upload/image/dti-hospital/ic_recipe_notice.png"></image>
				<view class="notice-text">订单中的处方药需医生问诊开方，请先预约。</view>
			</view>
			<view class="bottom-triangle"></view>
		</view>
		<view v-if="inquiryShow" class="inquiry-root">
			<view class="inquiry-dialog">
				<image class="close-btn" src="https://res.jiuzhang-cloud.com/jzy-oss/upload/image/dti-hospital/ic_float_close.png" @click="showOrHideinquiry()"></image>
				<image class="notice-pic" src="https://res.jiuzhang-cloud.com/jzy-oss/upload/image/dti-hospital/ic_cart_inquiry.png"></image>
				<view class="notice-title">温馨提示</view>
				<view class="notice-content">购物清单有处方药，需要问诊信息才能预约购买</view>
				<view class="inquiry-btn" @click="gotoRouter('/pages-inquiry/inquirySelect/inquirySelect?type=2')">去填写问诊信息</view>
			</view>
		</view>
	</view>
</template>

<script>
	import uEmptyState from '@/components/u-empty-state/u-empty-state.vue';
	export default {
		components: {
			uEmptyState
		},
		data() {
			return {
				allChecked: false,
				validList: [],
				invalidList: [],
				editMode: false,
				selectedTotalPrice: 0.00,
				hasRecipeCheck: false,
				inquiryShow: false,
				rememberIds: []
			};
		},
		onShow() {
			this.getCartList();
		},
		methods: {
			getCartList() {
				this.rememberMedicineCheck();
				this.$api.getCartList({}).then(res => {
					if (res.code == 200) {
						let tempValid = res.result.validList;
						tempValid.forEach((item, index) => {
							item.isChecked = this.rememberIds.includes(item.id);
						})
						this.validList = tempValid;
						this.invalidList = res.result.failureList;
						this.needCheckAll();
					}
				});
			},
			checkAll() {
				this.validList.forEach((item, index) => {
					item.isChecked = !this.allChecked;
				});
				this.needCheckAll();
			},
			checkMedicine(medicine) {
				medicine.isChecked = !medicine.isChecked;
				this.$forceUpdate();
				this.needCheckAll();
			},
			needCheckAll() {
				let isAllChecked = true;
				let price = 0.00;
				let hasRecipe = false;
				this.validList.forEach((item, index) => {
					if (!item.isChecked) {
						isAllChecked = false;
					} else {
						// 有勾选就计算价格
						price += item.salesPrice * item.count;
						if (item.recipeFlag > 0 && !hasRecipe) {
							hasRecipe = true;
						}
					}
				})
				this.allChecked = isAllChecked;
				this.selectedTotalPrice = price.toFixed(2);
				this.hasRecipeCheck = hasRecipe;
			},
			rememberMedicineCheck() {
				let tempIds = [];
				this.validList.forEach((item, index) => {
					if (item.isChecked) {
						tempIds.push(item.id);
					}
				})
				this.rememberIds = tempIds;
			},
			showCountInput(medicine) {
				uni.showModal({
					title:"输入数量",
					editable:true,
					placeholderText:'请输入',
					success: res => {
						var numReg = /^[0-9]+$/
						var numRe = new RegExp(numReg)
						if (!numRe.test(res.content)) {
						    uni.showToast({
						    	title:'请输入数字',
								icon:'none'
						    })
						} else {
							this.changeCount(medicine, res.content)
						}
					}
				})
			},
			changeCount(medicine, count) {
				if (count <= 0) {
					this.deleteMedicine(medicine);
				} else {
					this.$api.changeCartCount({
						data: {
							commodityId: medicine.id,
							count
						}
					}).then(res => {
						if (res.code == 200) {
							this.getCartList();
						} else {
							uni.showToast({
								title: res.message,
								icon:'none'
							});
						}
					})
				}
			},
			toEdit() {
				this.editMode = !this.editMode;
				this.validList.forEach((item, index) => {
					item.isChecked = false;
				})
				this.allChecked = false;
				this.selectedTotalPrice = 0.00;
			},
			doConfirm() {
				if (this.editMode) {
					this.deleteCheckedMedicine();
				} else if (this.hasRecipeCheck) {
					this.showOrHideinquiry();
				} else {
					let noCheck = true;
					let checkedMedicines = [];
					this.validList.forEach((item, index) => {
						if (item.isChecked) {
							noCheck = false;
							checkedMedicines.push(item);
						}
					})
					if (noCheck) {
						uni.showToast({
							title:"请选择药品",
							icon:'none'
						});
						return;
					} else {
						uni.navigateTo({
							url:'/pages-mall/orderCreate/orderCreate?medicines=' + JSON.stringify(checkedMedicines)
						})
					}
				}
			},
			deleteCheckedMedicine() {
				let idList = [];
				this.validList.forEach((item, index) => {
					if (item.isChecked) {
						idList.push(item.id);
					}
				});
				if (idList.length == 0) {
					uni.showToast({
						title:"请选择需要删除的药品",
						icon:'none'
					});
					return;
				}
				this.$api.deleteFromCart({
					params: {
						ids: idList.join()
					}
				}).then(res => {
					if (res.code == 200) {
						this.getCartList();
					} else {
						uni.showToast({
							title:res.message,
							icon:'none'
						});
					}
				})
			},
			deleteMedicine(medicine) {
				this.$api.deleteFromCart({
					params: {
						ids: medicine.id
					}
				}).then(res => {
					if (res.code == 200) {
						this.getCartList();
					} else {
						uni.showToast({
							title:res.message,
							icon:'none'
						});
					}
				})
			},
			clearAllInvalid() {
				uni.showModal({
					title: `确认要删除所有失效药品吗？`,
					success: res => {
						if (res.confirm) {
							let idList = [];
							this.invalidList.forEach((item, index) => {
								idList.push(item.id);
							});
							this.$api.deleteFromCart({
								params: {
									ids: idList.join()
								}
							}).then(res => {
								if (res.code == 200) {
									this.getCartList();
								} else {
									uni.showToast({
										title:res.message,
										icon:'none'
									});
								}
							})
						}
					}
				});
			},
			clearAllMedicine() {
				uni.showModal({
					title: `确认要删除所有药品吗？`,
					success: res => {
						if (res.confirm) {
							let idList = [];
							this.validList.forEach((item, index) => {
								idList.push(item.id);
							})
							this.invalidList.forEach((item, index) => {
								idList.push(item.id);
							});
							this.$api.deleteFromCart({
								params: {
									ids: idList.join()
								}
							}).then(res => {
								if (res.code == 200) {
									this.getCartList();
									this.toEdit();
								} else {
									uni.showToast({
										title:res.message,
										icon:'none'
									});
								}
							})
						}
					}
				});
			},
			showOrHideinquiry() {
				this.inquiryShow = !this.inquiryShow;
			}
		}
	}
</script>

<style lang="less" scoped>
@import './medicineCart.less';
</style>
